package com.woniu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.entity.Student1;
import com.woniu.pojo.Class;
import com.woniu.pojo.Student;
import com.woniu.service.ClassService;
import com.woniu.service.StudentService;
import com.woniu.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("student")
public class StudentController {

    @Autowired
    StudentService studentService;
    @Autowired
    ClassService classService;

    //展示页面跳转
    @RequestMapping("listJump")
    public String listJump(){
        return "WEB-INF/student/list";
    }

    //展示毕业学员页面跳转
    @RequestMapping("graduatedList")
    public String graduatedListJump(){
        return "WEB-INF/student/graduatedList";
    }

    //增加页面跳转
    @RequestMapping("addJump")
    public String addJump(Model model){
        List<Class> classList = classService.selectAll();
        model.addAttribute("classList",classList);
        return "WEB-INF/student/add";
    }

    //增加公司
    @RequestMapping("add")
    @ResponseBody
    public Map<String, Object> add(Student student){
        Map<String, Object> map = new HashMap<String,Object>();
        try {
            studentService.add(student);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }


    //按主键 删除学生
    @RequestMapping("deleteById")
    @ResponseBody
    public Map<String,Object> deleteById(Integer studentId){
        Map<String, Object> map=new HashMap<String,Object>();
        try {
            studentService.deleteById(studentId);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    //查询一个学生
    @ResponseBody
    @RequestMapping("findOne")
    public Map<String,Object> findOne(Integer studentId, Model model){
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Student1 student = studentService.findOne(studentId);
            map.put("student",student);
            map.put("result","ok");
        }catch(Exception e){
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    //跳转到修改
    @RequestMapping("updateJump")
    public String updateJump(Model model, Integer studentId){
        Student1 student = studentService.findOne(studentId);
        List<Class> classList = classService.selectAll();

        model.addAttribute("student",student);
        model.addAttribute("classList",classList);

        return "WEB-INF/student/update";
    }
    //跳转到修改1  仅修改个人信息
    @RequestMapping("updateJump1")
    public String updateJump1(Model model, Integer studentId){
        Student1 student = studentService.findOne(studentId);
        model.addAttribute("student",student);
        return "WEB-INF/info/updateInfo";
    }

    //修改学生信息
    @ResponseBody
    @RequestMapping("update")
    public Map<String, Object> update(Student student){
        Map<String, Object> map=new HashMap<String,Object>();
        try {
            studentService.updateById(student);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 学生查询(模糊查询)分页
     * @param pageNum
     * @param pageSize
     * @param student 模糊查询封装
     * @return
     */
    @RequestMapping("findAll")
    @ResponseBody
    public Map<String, Object> findAll(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize",defaultValue ="6") Integer pageSize, Student student){
        Map<String, Object> map=new HashMap<String,Object>();
        try {
            PageHelper.startPage(pageNum,pageSize);
            List<Student1> studentList = studentService.findAll(student);
            List<Class> classList = classService.selectAll();

            PageInfo<Student1> pageInfo=new PageInfo<Student1>(studentList);
            map.put("pageInfo",pageInfo);
            map.put("studentList",studentList);
            map.put("classList",classList);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("findGraduatedStudent")
    @ResponseBody
    public Map<String, Object> findGraduatedStudent(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize",defaultValue ="6") Integer pageSize, Student student){

        System.out.println("================================================");
        System.out.println("student = " + student);

        Map<String, Object> map=new HashMap<String,Object>();
        try {
            PageHelper.startPage(pageNum,pageSize);
            List<Student1> studentList = studentService.findGraduatedStudents(student);
            List<Class> classList = classService.selectAll();

            PageInfo<Student1> pageInfo=new PageInfo<Student1>(studentList);
            map.put("pageInfo",pageInfo);
            map.put("studentList",studentList);
            map.put("classList",classList);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    //学生批量删除
    @RequestMapping("deleteByExample")
    @ResponseBody
    public Map<String,Object> deleteByExample(Integer[] studentIds){
        Map<String, Object> map=new HashMap<String,Object>();
        try {
            studentService.deleteByExample(Arrays.asList(studentIds));
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("exportStudent")
    public void exportStudent(HttpServletRequest request,HttpServletResponse response){
        List<Student1> studentList = studentService.findAll(null);
        String[] title = {"ID","姓名","性别","班级","电话","地址","入学时间","学分"};
        String fileName = "student.xls";
        String sheetName = "sheet1";
        String[][] content = new String[studentList.size()][8];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            for (int i = 0;i < studentList.size();i++){
                    content[i][0] = String.valueOf(studentList.get(i).getStudentId());
                    content[i][1] = studentList.get(i).getStudentName();
                    content[i][2] = studentList.get(i).getStudentSex();
                    content[i][3] = studentList.get(i).getClassId().getClassName();
                    content[i][4] = studentList.get(i).getStudentPhone();
                    content[i][5] = studentList.get(i).getStudentAddress();
                    content[i][6] = sdf.format(studentList.get(i).getStudentIntotime());
                    content[i][7] = String.valueOf(studentList.get(0).getStudentGrade());
            }
        } catch (Exception e){
            e.printStackTrace();
        }

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);
        try {
            this.setResponseHeader(response,fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            fileName = new String(fileName.getBytes(),"utf-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/uploadImage")
    @ResponseBody
    public String importExcel(@RequestParam(value="studentImg",required = false) MultipartFile studentImg, Integer studentId,HttpServletRequest request){
        String flag = "01";// 上传标志
        try {
            // 保存图片的路径，图片上传成功后，将路径保存到数据库
            String filePath = request.getSession().getServletContext().getRealPath("upload");
            File file = new File(filePath);
            if (!file.exists()){
                file.mkdir();
            }
            // 获取原始图片的扩展名
            String originalFilename = studentImg.getOriginalFilename();
            // 生成文件新的名字
            String newFileName = UUID.randomUUID() + originalFilename;
            // 封装上传文件位置的全路径
            File targetFile = new File(filePath, newFileName);
            studentImg.transferTo(targetFile);
            // 保存到数据库u
            Student student = studentService.findOne1(studentId);
            student.setStudentImg("upload/" + newFileName);
            studentService.updateById(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

}
